/*
 *  Copyright 2012 Anton Van Zyl. http://code.google.com/p/java-swiss-knife/
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.knife.File;

import java.io.File;
import java.io.IOException;

/**
 * This is Util for safely handeling Files on a system. <br/>
 * <br/>
 * Please visit <a
 * href="http://code.google.com/p/java-swiss-knife/">Java-Swiss-Knife</a> and
 * comment, rate, contribute or raise a issue/enhancement for my library. <br/>
 * 
 * @author Anton Van Zyl
 * 
 */
public class FileUtil {

	/**
	 * Creates the file, checking if the file exist and if so, depending on the
	 * field input, the file will be overwritten or not.
	 * 
	 * @param fileToCreate
	 * @param overwriteFile
	 * @return boolean - has File Been Deleted
	 * @throws IOException
	 */
	public static boolean createFile(File fileToCreate, boolean overwriteFile) throws IOException {
		if (fileToCreate.exists() && overwriteFile) {
			delete(fileToCreate);
			return fileToCreate.createNewFile();
		} else if (!fileToCreate.exists()) {
			return fileToCreate.createNewFile();
		}
		System.out.println("Could not create file [fileToCreate=" + fileToCreate + ";fileExist=" + fileToCreate.exists() + ";overwriteFile=" + overwriteFile + ";]");
		return false;
	}

	/**
	 * This will delete the File or Folder structure completely.
	 * 
	 * @param fileToDelete
	 * @throws IOException
	 */
	public static void delete(File fileToDelete) throws IOException {
		doDelete(fileToDelete);
	}

	private static void doDelete(File path) throws IOException {
		if (path.isDirectory()) {
			for (File child : path.listFiles()) {
				doDelete(child);
			}
		}
		if (!path.delete()) {
			throw new IOException("Could not delete " + path);
		}
	}

}
